package cn.clx.ymcc.listener;

import cn.clx.ymcc.domain.PayOrder;
import cn.clx.ymcc.dto.PayNotifyDto;
import cn.clx.ymcc.exception.GlobalException;
import cn.clx.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 支付宝回调，支付成功，开启的广播，让Order服务，和Course服务修改相应数据
 */
@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup="service-pay-to-course-order-producer")
public class PaySuccessToCourseAndOrderListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;

    /**
     * 执行本地事务
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            if(arg==null){
                throw new GlobalException("消息发送失败");
            }
            PayOrder payOrder= (PayOrder) arg;
            PayOrder payOrdertem = payOrderService.checkPayOrder(payOrder.getOrderNo());
            if(payOrdertem.getPayStatus()!=PayOrder.STATE_WAIT_PAY){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            payOrderService.updateById(payOrder);
            log.info("本地事务执行成功");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 回查本地事务是否成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] payload = (byte[]) message.getPayload();
            String JsonStr = new String(payload, StandardCharsets.UTF_8);
            PayNotifyDto dto = JSONObject.parseObject(JsonStr, PayNotifyDto.class);
            if(dto==null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            PayOrder payOrder = payOrderService.checkPayOrder(dto.getOrderNo());
            if(payOrder.getPayStatus()==PayOrder.STATE_PAY_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
